package com.xsjiong.jaript;

import com.xsjiong.jaript.utils.JReflector;

import java.util.ArrayList;
import java.util.HashMap;

public class JImportHelper {
	private ArrayList<String> ImportedPackages = new ArrayList<>();
	private HashMap<String, String> ImportedClasses = new HashMap<>();

	public JImportHelper() {
	}

	public void importPackage(String s) {
		if (s.charAt(s.length() - 1) != '.') s += '.';
		if (!ImportedPackages.contains(s))
			ImportedPackages.add(s);
	}

	public void unimportPackage(String s) {
		ImportedPackages.remove(s);
	}

	public void importClass(String s) {
		ImportedClasses.put(s.substring(s.lastIndexOf('.') + 1), s);
	}

	public void unimportClass(String s) {
		ImportedClasses.remove(s);
	}

	public void clearImportedPackages() {
		ImportedPackages.clear();
	}

	public void clearImportedClasses() {
		ImportedClasses.clear();
	}

	public void clearImports() {
		ImportedPackages.clear();
		ImportedClasses.clear();
	}

	public String expandClassName(String s) {
		if (s.indexOf('.') != -1) return s;
		String tmp;
		for (int i = 0; i < ImportedPackages.size(); i++)
			if (JReflector.getClassSafely(tmp = (ImportedPackages.get(i) + s)) != null) return tmp;
		tmp = ImportedClasses.get(s);
		if (tmp != null) return tmp;
		return s;
	}

	public Class<?> getClassBySimpleName(String s) throws ClassNotFoundException {
		s = expandClassName(s);
		Class<?> c = JReflector.getClassSafely(s);
		if (c != null) return c;
		throw new ClassNotFoundException(s);
	}
}
